package com.example.dc.Service.Impl;

import com.example.dc.domain.*;
import com.example.dc.mapper.ChatMapper;
import com.example.dc.Service.ChatService;
import com.example.dc.mapper.UserMapper;
import com.example.dc.utils.SparkAPI;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import com.example.dc.utils.HttpURLConnectionUtils;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatMapper chatMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public String postResult(ChatBean chatBean) {
        List<Chat> chatList = chatBean.getList();
        int len = chatList.size();
        SparkAPI sparkAPI = new SparkAPI();
        JsonArray jsonArray = new JsonArray();
        for (int i = 0; i < chatList.size(); i++) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("role", chatList.get(i).getRole());
            jsonObject.addProperty("content", chatList.get(i).getContent());
            jsonArray.add(jsonObject);
        }
        String answer = sparkAPI.Test(jsonArray);
        //将question和answer插入到数据库中
        chatMapper.insertContent(chatBean.getUserId(), chatList.get(len - 1).getContent(), answer);
        return answer;
    }

    public String getGreet(Integer userId, String location) {
        Random random = new Random();
        String name = getName(userId);
        String result = "#";
        int count = 0;
        while (result.equals("#") && count < 2) {   //防止重复调用接口
            int type = random.nextInt(2);
            if (count > 0 && type == 0) type += 1;
            System.out.println("type:"+type);
            switch (type) {
                case 0:
                    result = getGreetByWeather(userId, location);
                    break;
                case 1:
                    result = getGreetByTime();
                    break;
            }
            count++;
        }
        //将XXX替换为敬语
        if (result.indexOf("XXX") != -1) {
            result = result.replace("XXX", name);
        } else {
            result = name + "," + result;
        }

        return result;
    }

    //根据姓名、年龄、性别生成尊称
    public String getName(Integer userId) {
        User user = userMapper.getUserInfoByUserId(userId);
        Character surname = user.getNickname().charAt(0);
        Integer age = user.getAge();
        Character sex = user.getSex();
        String result = "" + surname;
        if (sex == '男') {
            if (age >= 55) result += "爷爷";
            else if (age > 30) {
                result += "叔叔";
            } else {
                result += "哥哥";
            }
        } else {
            if (age >= 55) result += "奶奶";
            else if (age > 30) {
                result += "阿姨";
            } else {
                result += "姐姐";
            }
        }
        return result;
    }


    //1.根据天气生成的问候语
    public String getGreetByWeather(Integer userId, String location) {
        if (location == null || location == "") return "#";
        //获取称呼
        String name = getName(userId);
        HttpURLConnectionUtils httpURLConnectionUtils = new HttpURLConnectionUtils();
        List<Weather> weatherList = httpURLConnectionUtils.sendGetRequest(location);
        if (weatherList == null) return "#";
        int startTemp = Integer.parseInt(weatherList.get(0).getTemp());
        String result = weatherList.get(0).toString();
        System.out.println("当前气温：" + weatherList.get(0).getTemp());
        if (Integer.parseInt(weatherList.get(0).getTemp()) < 20)
            result = "XXX," + "当前气温只有" + weatherList.get(0).getTemp() + "度，天冷了，记得保暖哦!多穿衣服";
        if (weatherList.get(0).getText().indexOf("雨") != -1) result = "XXX,下雨了，记得保暖哦!多穿衣服";
        else {
            for (int i = 1; i < weatherList.size(); i++) {
                int afterTemp = Integer.parseInt(weatherList.get(i).getTemp());
                if (startTemp - afterTemp >= 5 && i < 3) {
                    LocalDateTime now = LocalDateTime.now();
                    int hour = now.getHour();
                    result = "XXX，气温正在下降哦，" + (hour + i) + "点，气温只有" + afterTemp + "度了，要多穿衣服哦!不要冬着了";
                    break;
                } else if (weatherList.get(i).getText().indexOf("雨") != -1) {
                    result = "XXX," + i + "小时后会下雨，出门记得带伞哦";
                }
            }
        }
        return result;
    }

    //2.根据时间生成问候语
    public String getGreetByTime() {
        LocalDateTime now = LocalDateTime.now();
        int hour = now.getHour();
        int minute = now.getMinute();
        int second = now.getSecond();
        String result = "#";
        List<String> greetList = null;
        if (hour >= 5 && hour <= 10) {
            greetList = chatMapper.getGreet("时间", "早晨");
        } else if (hour >= 11 && hour <= 13) {
            greetList = chatMapper.getGreet("时间", "中午");
        }
        else if (hour >= 14 && hour <= 16) {
            greetList = chatMapper.getGreet("时间", "下午");
        }
        else if (hour >= 17 && hour <= 19) {
            greetList = chatMapper.getGreet("时间", "傍晚");
        } else if (hour >= 20 && hour <= 23) {
            greetList = chatMapper.getGreet("时间", "夜晚");
        }
        else{
            result="XXX,夜深了，早点休息哦";
        }
        if (greetList != null && greetList.size() > 0) {
            Random random = new Random();
            int index = random.nextInt(greetList.size());
            result = greetList.get(index);
        }
        return result;
    }

    //3.根据疾病生成的问候语
    public String getGreetBySickness() {

        return "#";
    }

    @Override
    public List<Chatgpt> getHistory(Integer userId){
        return chatMapper.getHistory(userId);
    }


    @Override
    public List<Chat> getHistoryByTime(Integer userId, String createTime){
        List<Chatgpt> chatgptList=chatMapper.getHistoryByTime(userId, createTime);
        List<Chat> chatList=new ArrayList<>();
        for(Chatgpt chatgpt:chatgptList){
            Chat chat =new Chat();
            chat.setRole("user");
            chat.setContent(chatgpt.getQuestion());
            chatList.add(chat);
            Chat chat2 =new Chat();
            chat2.setRole("assistant");
            chat2.setContent(chatgpt.getAnwser());
            chatList.add(chat2);
        }
        return chatList;
    }

}
